package org.example;

import jakarta.annotation.Resource;
import org.example.dto.ProductRequestDto;
import org.example.dto.ProductResponseDto;
import org.example.dto.ResultDto;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class ProductController {        //消费者模块
    @Resource RestTemplate restTemplate;
    @PostMapping("/api/product")
    @ResponseStatus(HttpStatus.CREATED)
    public void create(@RequestBody ProductRequestDto productRequest){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity entity = new HttpEntity(productRequest,headers);
        restTemplate.postForLocation("http://product-service/api/product",entity);

    }

    @GetMapping("/api/product")
    @ResponseStatus(HttpStatus.OK)
    public ResultDto<List<ProductResponseDto>> findAll(){
        //远程调用的对象解析出来
        ParameterizedTypeReference<ResultDto<List<ProductResponseDto>>> pt = new ParameterizedTypeReference<>() {};
       ResponseEntity<ResultDto<List<ProductResponseDto>>> exchange =
               restTemplate.exchange("http://product-service/api/product", HttpMethod.GET, HttpEntity.EMPTY,pt);
       return exchange.getBody();
    }
}
